//
//  LoginViewModel.swift
//  HinsLive
//
//  Created by haoxian on 2019/4/20.
//  Copyright © 2019 Hins. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa


class LoginViewModel {
    
    let loginEnable: Driver<Bool>

    init(accountDriver: Driver<String>,
         passwordDriver: Driver<String>) {
        
        let accountAvailable = accountDriver.map { $0.count > 0 }
        let passwordAvailable = passwordDriver.map { $0.count > 0 }
        loginEnable = Driver.combineLatest(accountAvailable, passwordAvailable) { $0 && $1 }
    }
    
    var loginTap: ((String, String)) -> Observable<Event<UserInfo>> {
        return { args in
            return Network.login(LoginRequest.build(args))
                .preDo(onNext: {  AccountManager.share.login(with: $0) })
                .observeOn(MainScheduler.asyncInstance)
        }
    }
}

private extension LoginRequest {
    static func build(_ args: (String, String)) -> LoginRequest {
        return LoginRequest.with { req in
            req.account = args.0
            req.password = args.1
        }
    }
}
